package com.cgbsoft.financial;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemLongClickListener;

import com.cgbsoft.financial.charts.SpendMoneyLineChartActivity;
import com.cgbsoft.financial.common.ConfigurationManager;
import com.cgbsoft.financial.dao.MyTransactionDB;
import com.cgbsoft.financial.dao.TransactionFileManager;
import com.cgbsoft.financial.domain.MyTransaction;
import com.cgbsoft.financial.update.UpdateApplication;
import com.cgbsoft.financial.utils.DateUtil;
import com.cgbsoft.financial.utils.StringUtils;
//import com.waps.AppConnect;
import com.umeng.analytics.MobclickAgent;

public class FinancialActivity extends Activity implements AdapterView.OnItemClickListener, OnClickListener, OnItemLongClickListener {
	
	public static String transactionFilePath = Environment.getExternalStorageDirectory() + "/data/financial/financial.xml";
	
	public static boolean isCheckUpdate = false;
	
	private static final int SET_PASSWORD = 0;
	private static final int CHECK_ANALYZE_VIEW = 1;
	private static final int SETTING = 2;
	private static final int EXIT = 3;
	
	private static String TAG = "FinancialActivity";
	
	private ListView transactionList;
	private Button preMonth, currentMonth, nextMonth;
	private ImageView transactionAdd;
	
	private static List<MyTransaction> totalTransactionList;
	
	private static List<MyTransaction> showTransactionList = new ArrayList<MyTransaction>();
	
	List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	
	public SimpleAdapter sa;
	
    public static long lastTransactionId  = 999999;

    public ProgressDialog pd_loading;//进度条对话框
    
    //收支统计
    BigDecimal inCome = new BigDecimal("0");
	BigDecimal outCome = new BigDecimal("0");
	BigDecimal balance = new BigDecimal("0");
	
	//收支情况
	TextView inComeView, outComeView, balanceView;
	
	//搜索开始日期
	private String dateStart = ""; 
	//搜索结束日期
	private String dateEnd = ""; 

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.transaction_list);
        
        transactionList = (ListView) findViewById(R.id.transaction_list);
        transactionAdd = (ImageView) findViewById(R.id.transaction_add);
        
        inComeView = (TextView)findViewById(R.id.inCome);
        outComeView = (TextView)findViewById(R.id.outCome);
        balanceView = (TextView)findViewById(R.id.balance);
        
        preMonth = (Button) findViewById(R.id.preMonth);
        currentMonth = (Button) findViewById(R.id.currentMonth);
        nextMonth = (Button) findViewById(R.id.nextMonth);
        nextMonth.setEnabled(false);//一开始没有下个月
        
        transactionAdd.setOnClickListener(this);
        transactionList.setOnItemLongClickListener(this);
        preMonth.setOnClickListener(this);
        currentMonth.setOnClickListener(this);
        nextMonth.setOnClickListener(this);
		
		//初始数据
		initData();
		
		//开启线程检查更新
		if (!isCheckUpdate) {
			Log.i(TAG, "check update");
			UpdateApplication.checkVersion(this);
		}
        
		//启动广告统计平台
//		AppConnect.getInstance(this);
		
		pd_loading = new ProgressDialog(this);
		pd_loading.setCancelable(true);
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	MobclickAgent.onResume(this);
    	//再次初始数据
		initData();
    }
    
    @Override
    public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}
	
    
    /* 
	 * 菜单
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    public boolean onCreateOptionsMenu(Menu menu) {  
		//MenuInflater inflater = getMenuInflater();  
		//inflater.inflate(R.menu.menu,  menu); 
		
		menu.add(0, SET_PASSWORD, 0, "设置密码").setIcon(this.getResources().getDrawable(R.drawable.password));  
	    menu.add(0, CHECK_ANALYZE_VIEW, 1, "图表分析").setIcon(this.getResources().getDrawable(R.drawable.chart));   
	    menu.add(0, SETTING, 2, "偏好设置").setIcon(this.getResources().getDrawable(R.drawable.setting)); 
	    menu.add(0, EXIT, 3, "退出应用").setIcon(this.getResources().getDrawable(R.drawable.exit));   
		return true;  
	} 
    public boolean onOptionsItemSelected(MenuItem item) {  
		switch (item.getItemId()) {  
			case SET_PASSWORD:
				Intent passwordIntent = new Intent(FinancialActivity.this, PasswordSetting.class);
				startActivity(passwordIntent);
				break;
			case CHECK_ANALYZE_VIEW:
				Intent intent = new Intent(FinancialActivity.this, SpendMoneyLineChartActivity.class);
				SpendMoneyLineChartActivity.initData(totalTransactionList);
				startActivity(intent);
				break;
			case SETTING:
				Intent settingIntent = new Intent(FinancialActivity.this, SystemSetting.class);
				startActivity(settingIntent);
				break;
			case EXIT:
				this.finish();
				break;
			default:
				break;
		}
		return false; 
	}
    
    public void renderData(List<MyTransaction> inputtransactionList){
    	data.clear();
		for (int j = 0; j < inputtransactionList.size(); j++) {
			MyTransaction transaction = inputtransactionList.get(j);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("transactionId", String.valueOf(transaction.getId()));
			map.put("dDate", transaction.getdDate().length() > 9 ? transaction.getdDate().substring(0, 10) : transaction.getdDate());
			map.put("iSum", formatMoney(transaction.getiSum()));
			map.put("sSubject", transaction.getsSubject());
			map.put("cCatagory", transaction.getcCatagory());
			
			data.add(map);
		}
		
		sa = new SimpleAdapter(this, data, R.layout.transaction_row, new String[] {
				"transactionId", "dDate", "iSum", "cCatagory", "sSubject"},
				new int[] { R.id.transaction_id, R.id.d_date, R.id.i_sum,
						R.id.c_catagory, R.id.s_subject, });
		transactionList.setAdapter(sa);
		sa.notifyDataSetChanged();
		
		//统计收支
		clearCount();
		countTransactoin(inputtransactionList);
		inComeView.setText("收入：" + inCome.toString());
		outComeView.setText("支出：" + outCome.toString());
		balanceView.setText("盈余：" + balance.toString());
		
		//找出最大的ID
		FinancialActivity.lastTransactionId = findLastTransactionId();
	}
    
    private void initData() {
    	new Thread(new Runnable() { 
			@Override
			public void run() {
				//判断文件是否存在
				File file = new File(transactionFilePath);
		    	if (!file.exists()) {//如果文件不存在，创建一个
		    		TransactionFileManager.createEmptyXmlFile(file);
		    	}
		    	//读取事务列表
		    	if (file.exists()) {//文件存在，读取文件
		    		FinancialActivity.totalTransactionList = TransactionFileManager.readXML(transactionFilePath);
		    	} else {//否则使用数据库
		    		ConfigurationManager.getInstance(FinancialActivity.this).setBooleanConfig(ConfigurationManager.IF_DB_STORE, true);
		    		FinancialActivity.totalTransactionList = MyTransactionDB.findTransactions(FinancialActivity.this, null, null);
		    	}
				
				//排序
				sortTransactionList();
				
				Log.i("myTransactionList:", String.valueOf(totalTransactionList.size()));
				Message message=new Message();
				message.what=0;
				mHandler.sendMessage(message);
			}
		}).start();
    }
    
    Handler mHandler=new Handler(new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				//只显示当前月记录
				showTransactionList = getCurrentMonthTrsansaction();
				renderData(showTransactionList);
				break;
			default:
				break;
			}
			return false;
		}
});

    
    /**
     * 倒序排序
     */
    private void sortTransactionList() {
//    	List<MyTransaction> myTransactionListTemp = new ArrayList<MyTransaction>();
//    	myTransactionListTemp.addAll(totalTransactionList);
//    	totalTransactionList.clear();
//    	for (int i = myTransactionListTemp.size(); i > 0; i --) {
//    		totalTransactionList.add(myTransactionListTemp.get(i-1));
//    	}
    	Collections.sort(totalTransactionList, new Comparator<MyTransaction>() {
			@Override
			public int compare(MyTransaction arg0, MyTransaction arg1) {
				int result = 0;
				if ((!TextUtils.isEmpty(arg0.getdDate())) && (!TextUtils.isEmpty(arg0.getdDate()))) {
					result = arg1.getdDate().compareTo(arg0.getdDate());
				}
				if (result == 0) {
					result = Long.valueOf(arg1.getId()).compareTo(Long.valueOf(arg0.getId()));
				}
				return result;
			}
		});
    }
    
    
    private String formatMoney(String moneyStr) {
    	if (moneyStr.length() > 2) {
    		String intStr = moneyStr.substring(0, moneyStr.length()-2);
        	String decStr = moneyStr.substring(moneyStr.length()-2, moneyStr.length());
        	return intStr + "." + decStr;
    	} else {
    		return moneyStr;
    	}
    }
    
    private long findLastTransactionId() {
    	long lastTransactionId = 0;
    	for (MyTransaction myTransaction : totalTransactionList) {
    		if (lastTransactionId < myTransaction.getId()) {
    			lastTransactionId = myTransaction.getId();
    		}
    	}
    	return lastTransactionId;
    }


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.transaction_add: {
				Intent intent = new Intent(FinancialActivity.this, TransactionAdd.class);
				startActivity(intent);
				break;
			}
			case R.id.preMonth: {
				showTransactionList = getPreMonthTrsansaction();
				renderData(showTransactionList);
				nextMonth.setEnabled(true);
				break;
			}
			case R.id.currentMonth: {
				showTransactionList = getCurrentMonthTrsansaction();
				renderData(showTransactionList);
				nextMonth.setEnabled(false);
				break;
			}
			case R.id.nextMonth: {
				showTransactionList = getNextMonthTrsansaction();
				renderData(showTransactionList);
				//如果没有下个月记录，设置不可点击
				if(!hasNextMonth()) {
					nextMonth.setEnabled(false);
				}
				break;
			}
		}
	}

	public void setTransactionFilePath(String transactionFilePath) {
		FinancialActivity.transactionFilePath = transactionFilePath;
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View v, int arg2,
			long arg3) {
		final String transactionId = ((TextView)v.findViewById(R.id.transaction_id)).getText().toString();
		final String transactiondate = ((TextView)v.findViewById(R.id.d_date)).getText().toString();
		final String transactionSummary = ((TextView)v.findViewById(R.id.s_subject)).getText().toString();
		final String transactionMoney = ((TextView)v.findViewById(R.id.i_sum)).getText().toString();
		final String transactionCatagory = ((TextView)v.findViewById(R.id.c_catagory)).getText().toString();
		
		String[] selectItems = new String[] {"修改", "删除"};
		new AlertDialog.Builder(FinancialActivity.this)
        .setTitle("选择操作")
        .setItems(
        		selectItems,
        		new DialogInterface.OnClickListener() {
	              public void onClick(DialogInterface dialog, int whichItem) {        
	            	  switch (whichItem) {
	            	  	case 0:
	            	  		Log.i(TAG, "修改：" + transactionId);
	            	  		Intent modifyIntent = new Intent(FinancialActivity.this, TransactionModify.class);
	            	  		modifyIntent.putExtra("transactionId", transactionId);
	            	  		modifyIntent.putExtra("transactiondate", transactiondate);
	            	  		modifyIntent.putExtra("transactionSummary", transactionSummary);
	            	  		modifyIntent.putExtra("transactionMoney", transactionMoney);
	            	  		modifyIntent.putExtra("transactionCatagory", transactionCatagory);
	            	  		startActivity(modifyIntent);
	            	  		break;
		  				case 1:
		  					Log.i(TAG, "删除：" + transactionId);
		  					deleteTransaction(transactionId);
		  					break;
		  				default:
		  					break;
		  			}
	              }
	            })
        .show();
		return false;
	}
	
	private void deleteTransaction(final String transactionId) {
    	pd_loading.setMessage("删除中...");
    	pd_loading.show();
    	new Thread(
				new Runnable() { 
					public void run() {
						if (ConfigurationManager.getInstance(FinancialActivity.this).getBooleanConfig(ConfigurationManager.IF_DB_STORE, false)) {
							//从数据库中删除
							MyTransactionDB.deleteMyTransactionById(FinancialActivity.this, transactionId);
						} else {
							//从xml中删除
							TransactionFileManager.deleteTransaction(transactionId);
						}
				        
				        if (pd_loading.isShowing()) {
				        	pd_loading.dismiss();
				        }
				        
				        initData();//重新加载数据
					} 
				}).start();	
    }
	
	/**
	 * @param transactionId
	 */
	private void removeTransactionById(String transactionId) {
		for (MyTransaction transaction : totalTransactionList) {
			if (transactionId.equalsIgnoreCase(String.valueOf(transaction.getId()))) {
				totalTransactionList.remove(transaction);
			}
		}
	}
	
	/**
	 * 查找两个日期之间的记录
	 * @return
	 */
	private List<MyTransaction> findTransactionByDate(String dateFrom, String dateTo) {
		List<MyTransaction> transactions = new ArrayList<MyTransaction>();
		
		for (MyTransaction transaction : totalTransactionList) {
			if (!StringUtils.isNULL(transaction.getdDate()) && transaction.getdDate().length() >= 10) {
				if ((transaction.getdDate().compareTo(dateFrom) > 0 || transaction.getdDate().compareTo(dateFrom) == 0) 
						&& transaction.getdDate().compareTo(dateTo) < 0 || transaction.getdDate().compareTo(dateTo) == 0) {
					transactions.add(transaction);
				}
			}
		}
		
		return transactions;
	}
	
	/**
	 * 找当前月的记录
	 * @return
	 */
	private List<MyTransaction> getCurrentMonthTrsansaction() {
		String currentDate = DateUtil.getDate();
		String currentMothFirstDate = currentDate.substring(0, currentDate.length()-2) + "01";
		String currentMothMaxDate = currentDate.substring(0, currentDate.length()-2) + "31";
		dateStart = currentMothFirstDate;
		dateEnd = currentMothMaxDate;
		return findTransactionByDate(currentMothFirstDate, currentMothMaxDate);
	}
	
	/**
	 * 查找上一个月的记录
	 * @return
	 */
	private List<MyTransaction> getPreMonthTrsansaction() {
		String preMonthDate = DateUtil.addMonth(dateStart, -1);
		
		String searchMothFirstDate = preMonthDate.substring(0, preMonthDate.length()-2) + "01";
		String searchMothMaxDate = preMonthDate.substring(0, preMonthDate.length()-2) + "31";
		dateStart = searchMothFirstDate;
		dateEnd = searchMothMaxDate;
		return findTransactionByDate(searchMothFirstDate, searchMothMaxDate);
	}
	
	/**
	 * 查找下一个月的记录
	 * @return
	 */
	private List<MyTransaction> getNextMonthTrsansaction() {
		String nextMonthDate = DateUtil.addMonth(dateStart, 1);
		
		String searchMothFirstDate = nextMonthDate.substring(0, nextMonthDate.length()-2) + "01";
		String searchMothMaxDate = nextMonthDate.substring(0, nextMonthDate.length()-2) + "31";
		dateStart = searchMothFirstDate;
		dateEnd = searchMothMaxDate;
		return findTransactionByDate(searchMothFirstDate, searchMothMaxDate);
	}
	
	/**
	 * 是否是最后一个月
	 * @return
	 */
	private boolean hasNextMonth() {
		String currentDate = DateUtil.getDate();
		String nextMonthDate = DateUtil.addMonth(dateStart, 1);
		if (currentDate.compareTo(nextMonthDate) < 0) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * type:0收入，1支出，2盈余
	 * @param type
	 * @return
	 */
	private void countTransactoin(List<MyTransaction> countTransactionList) {
		for (MyTransaction trsaction : countTransactionList) {
			String iSum = trsaction.getiSum();
			try {
				char single = iSum.charAt(0);
				if (single != '-') {
					if (single == '+') {
						iSum = iSum.substring(1, iSum.length());
					}
					inCome = inCome.add(new BigDecimal(iSum));
				} else {
					iSum = iSum.substring(1, iSum.length());
					outCome = outCome.add(new BigDecimal(iSum));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		balance = inCome.subtract(outCome);
		
		inCome = inCome.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
		outCome = outCome.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
		balance = balance.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
	}
	
	private void clearCount() {
		inCome = new BigDecimal("0");
		outCome = new BigDecimal("0");
		balance = new BigDecimal("0");
	}
	
}